package com.hn.utils.timing;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hn.Entry.MapEntry;
import com.hn.Entry.ServerOrderEntry;
import com.hn.Entry.UserOrderEntry;
import com.hn.common.ShareData;
import com.hn.utils.file.FileUtil;
import com.hn.utils.http.CatApiUtil;
import com.hn.utils.http.DateUtils;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.message.data.At;
import net.mamoe.mirai.message.data.Image;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import net.mamoe.mirai.utils.ExternalResource;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

public class TimingUtil {

    //每天0点调用的定时任务
    public void startTimedTasks(int Hour,int Minute,int Second,File MapFile){
        ShareData instance = ShareData.getInstance();
        // 获取当前日期和时间
        Calendar calendar = Calendar.getInstance();
        // 设置定时任务的时间
        calendar.set(Calendar.HOUR_OF_DAY, Hour);
        calendar.set(Calendar.MINUTE, Minute);
        calendar.set(Calendar.SECOND, Second);
        calendar.set(Calendar.MILLISECOND, 0);
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                clearAndOpen(instance);
            }
        };
        Timer timer=new Timer();
        //重复24小时
        timer.scheduleAtFixedRate(task,calendar.getTime(),24*60*60*1000);
    }
    //每30分钟调用的定时器任务
    public void startFiveMinutesTasks(File MapFile){
        ShareData instance = ShareData.getInstance();
        // 创建一个定时器
        Timer timer = new Timer();
        // 创建一个定时器任务
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                // 保存娶群友列表
                LinkedHashMap<Long, Long> marryMap = instance.getMarryMap();
                if (!marryMap.isEmpty()){
                    FileUtil.saveMap(marryMap,MapFile);
                }
                // 删除订婚
                instance.setDingHunList(new ArrayList<>());
                // 删除小三
                instance.setXiaoSanList(new ArrayList<>());
                // 删除离婚
                instance.setLiHunList(new ArrayList<>());
                System.out.println("三小时定时任务被调用...");
            }
        };
        // 设置定时器任务的时间间隔为5分钟（300000毫秒）
        timer.scheduleAtFixedRate(task, 0, 60*60*1000);
    }
    //每5s调用的定时器任务
    public void startFiveSecondsTasks(){
        ShareData instance = ShareData.getInstance();
        // 创建一个定时器
        Timer timer = new Timer();
        // 创建一个定时器任务
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                // 获取当前时间（开始时间）
                long startTime = System.currentTimeMillis();
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("https://www.bluearchive.top/api/blog/server/steamApi")
                        .build();
                try (Response response = client.newCall(request).execute()) {
                    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                    //用户订阅列表
                    List<ServerOrderEntry> serverOrderEntryList = instance.getServerOrderEntryList();
                    //当前登录的Bot
                    Bot bot = instance.getBot();
                    if (bot == null){
                        return;
                    }
                    //获取所有地图
                    Map<String, MapEntry> mapEntryMap = CatApiUtil.getMap();
                    // 服务器返回的是Map
                    Map<String,String> queryMap = JSON.parseObject(response.body().string(), HashMap.class);
                    sendOrderMessByGroup(queryMap,mapEntryMap,serverOrderEntryList,bot);
                    long endTime = System.currentTimeMillis();
                    long elapsedTime = endTime - startTime;
                    // 输出方法执行时间
                    System.out.println("获取服务器信息耗时 : " + elapsedTime + "毫秒");
                }catch (Exception e){
                    System.out.println("服务器通知失败!"+e);
                }
            }
        };
        // 设置定时器任务的时间间隔为3s
        timer.scheduleAtFixedRate(task, 0, 3000);
    }

    /**
     *
     * @param queryMap 服务器端的服务器数据
     * @param mapEntryMap 地图数据
     * @param serverOrderEntryList 用户订阅数据
     * @param bot 机器人发送消息对象
     */
    public synchronized void sendOrderMessByGroup(Map<String,String> queryMap,Map<String, MapEntry> mapEntryMap,List<ServerOrderEntry> serverOrderEntryList,Bot bot){
        queryMap.forEach((key, value) -> {
            if (key.equals("4")){
                return;
            }
            JSONArray jsonArray = JSON.parseArray(value);
            for (Object element : jsonArray) {
                JSONObject responseObject = ((JSONObject) element).getJSONObject("response");
                JSONArray serversArray = responseObject.getJSONArray("servers");
                if (serversArray == null){
                    continue;
                }
                for (Object server : serversArray) {
                    JSONObject serverObject = (JSONObject) server;
                    if (serverObject!=null){
                        //查看当前地图有没有玩家订阅
                        String map = serverObject.getString("map");
                        String name = serverObject.getString("name");
                        String playes=serverObject.getString("players");
                        String maxPlayes=serverObject.getString("max_players");
                        String addr=serverObject.getString("addr");
                        serverOrderEntryList.forEach(item->{
                            //用户ID列表
                            List<Long> userIdList = new ArrayList<>();
                            //文件上传 发送消息
                            Group group = bot.getGroup(item.getGroupId());
                            List<UserOrderEntry> userOrderList = item.getUserOrderList();
                            //遍历订阅用户列表 查看有没有用户订阅
                            for (UserOrderEntry userOrderEntry : userOrderList) {
                                //判断用户有没有偏好该社区
                                if (!userOrderEntry.getCommunityList().contains(key) && !userOrderEntry.getCommunityList().isEmpty()){
                                    continue;
                                }
                                //获取用户订阅地图信息
                                List<String> mapList = userOrderEntry.getMapList();
                                //地图通知列表
                                Map<String, Date> orderTimeMap = userOrderEntry.getOrderTimeMap();
                                if (orderTimeMap==null){
                                    orderTimeMap = new HashMap<>();
                                }
                                //遍历用户订阅的地图列表 查看有没有当前地图
                                for (String mapName : mapList) {
                                    //如果当前地图在用户订阅的地图列表中，则发送消息
                                    if (map.equals(mapName.trim())){
                                        //判断该地图是否已经三小时内发送过消息
                                        if(orderTimeMap.containsKey(addr) && !DateUtils.isEarlierThanThreeHours(orderTimeMap.get(addr))){
                                            return;
                                        };
                                        //添加用户进At列表
                                        userIdList.add(userOrderEntry.getUserId());
                                        //存储消息
                                        orderTimeMap.put(addr,new Date());
                                    }
                                }
                            }
                            if (userIdList.isEmpty()){
                                return;
                            }
                            //处理用户订阅 发送消息
                            MessageChainBuilder messageChainBuilder = new MessageChainBuilder();
                            MapEntry mapEntry = mapEntryMap.get(map);
                            if (mapEntry!=null){
                                //构建消息
                                messageChainBuilder.append("爱丽丝提醒你订阅的图出现了"+"\n");
                                messageChainBuilder.append("地图名:"+map+"("+mapEntry.getLabel()+")"+"\n");
                                messageChainBuilder.append("服务器名称: "+name+"("+playes+"/"+maxPlayes+")"+"\n");
                                messageChainBuilder.append("连接指令: "+"connect "+addr+"\n");
                                messageChainBuilder.append("网页端地址: "+"https://www.bluearchive.top"+"\n");
                                userIdList.forEach(userId->{
                                    messageChainBuilder.append(new At(userId));
                                });
                                messageChainBuilder.append("\n");
                                //添加地图图片
                                URL url = null;
                                try {
                                    if (mapEntry.getMapUrl() != null){
                                        url = new URL(mapEntry.getMapUrl());
                                        InputStream inputStream = url.openConnection().getInputStream();
                                        Image image = ExternalResource.uploadAsImage(inputStream, group);
                                        messageChainBuilder.append(image);
                                    }
                                } catch (Exception e) {
                                    System.out.println("地图图片获取失败");
                                }
                            }else{
                                //构建消息
                                messageChainBuilder.append("爱丽丝提醒你订阅的图出现了"+"\n");
                                messageChainBuilder.append("地图名:").append(map).append("(").append(mapEntry.getLabel()).append(")").append("\n");
                                messageChainBuilder.append("服务器名称: ").append(name).append("(").append(playes).append("/").append(maxPlayes).append(")").append("\n");
                                messageChainBuilder.append("连接指令: " + "connect ").append(addr).append("\n");
                                messageChainBuilder.append("网页端地址: "+"https://www.bluearchive.top");
                                userIdList.forEach(userId->{
                                    messageChainBuilder.append(new At(userId));
                                });
                                messageChainBuilder.append("\n");
                            }
                            //发送消息
                            group.sendMessage(messageChainBuilder.build());
                        });
                    }
                }
            }
        });
    }
    public void closeOpenTimedTasks(Timer timer){
        Calendar calendar = Calendar.getInstance();
        // 设置任务时间为明天的10点
        calendar.set(Calendar.HOUR_OF_DAY, 12);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 如果当前时间已经超过10点，则将日期设置为明天的日期
        if (calendar.get(Calendar.HOUR_OF_DAY) >= 12) {
            calendar.add(Calendar.DATE, 1);
        }
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                try {
                    // 执行定时任务逻辑
                    closeOpen();
                    // 重新调度任务到明天的同一时间
                    closeOpenTimedTasks(timer);
                } catch (Exception e) {
                    e.printStackTrace(); // 处理异常
                }
            }
        };
        // 调度任务到明天的10点
        timer.schedule(task, calendar.getTime());
    }
    public void clearAndOpen(ShareData instance){
        //清空群老婆列表
        instance.setMarryMap(new LinkedHashMap<>());
        //开启检测开关
        instance.setOpenProhibit(true);
    }
    public void closeOpen(){
        //关闭检测开关
        ShareData.getInstance().setOpenProhibit(false);
    }
}

